package com.example.myserializeprojects;

import androidx.appcompat.app.AppCompatActivity;

import android.content.res.AssetManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private final String TAG = "777777";
    Button btn;
    Button btn2;
    Button btn3;
    //下面的xml格式错误，运行报错
    String xmlData = "<apps>" +
            "<app>" +
            "<id>1</id>" +
            "<name>Google Maps<name/>" +
            "<version>1.0<version/>" +
            "</app>" +
            "<app>" +
            "<id>2</id>" +
            "<name>Chrome<name/>" +
            "<version>2.1<version/>" +
            "</app>" +
            "<app>" +
            "<id>3</id>" +
            "<name>Google Play<name/>" +
            "<version>2.3<version/>" +
            "</app>" +
            "</apps>";


    String xmldata2 = "<apps>\n" +
            "\t<app>\n" +
            "\t\t<id>1</id>\n" +
            "\t\t<name>Google Maps</name>\n" +
            "\t\t<version>1.0</version>\n" +
            "\t</app>\n" +
            "\t<app>\n" +
            "\t\t<id>2</id>\n" +
            "\t\t<name>Chrome</name>\n" +
            "\t\t<version>2.1</version>\n" +
            "\t</app>\n" +
            "\t<app>\n" +
            "\t\t<id>3</id>\n" +
            "\t\t<name>Google Play</name>\n" +
            "\t\t<version>2.3</version>\n" +
            "\t</app>\n" +
            "</apps>";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = findViewById(R.id.parse_xml_btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                parseXMLWithPull();

//                parseXmlWithSAX();

//                parseXMLWithPull2();  正确
//                parseXmlWithSAX2();  正确

            }
        });

        btn2 = findViewById(R.id.parse_json_btn);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                parswJsonWithJsonObject(); 正确
                parswJsonWithGson();
            }
        });

        btn3 = findViewById(R.id.parse_jsonArray_btn);
        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                parswJsonArrayWithGson();
            }
        });
    }

    private void parseXMLWithPull(){
        try {
            AssetManager assetManager = getAssets();
//            InputStream stream = assetManager.open("data.xml");
            InputStream stream = new ByteArrayInputStream(xmlData.getBytes(StandardCharsets.UTF_8));
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser pullParser = factory.newPullParser();
            pullParser.setInput(stream, "UTF-8");
            int eventType = pullParser.getEventType();
            String id = "", name = "", version = "";
            while (eventType != XmlPullParser.END_DOCUMENT){
                String nodeName = pullParser.getName();
                Log.e(TAG, "nodeName: "+nodeName );
                switch (eventType){
                    case XmlPullParser.TEXT:
                        Log.e(TAG, "TEXT: "+pullParser.nextText() );
                    case XmlPullParser.START_DOCUMENT:
                        Log.e(TAG, "START_DOCUMENT");
                        break;
                    case XmlPullParser.START_TAG:
                        if ("id".equals(nodeName)){
//                            Log.e(TAG, "id: start");
                            id = pullParser.nextText();
                            Log.e(TAG, "id "+id);
//                            pullParser.nextTag();
//                            if (pullParser.getEventType() != XmlPullParser.END_TAG) {
//                                Log.e(TAG, "2222222222222222222 " );
//                                pullParser.nextTag();
//                            }
//                            Log.e(TAG, "id: end");
                        } else if ("name".equals(nodeName)){
//                            Log.e(TAG, "name: start");
                            name = pullParser.nextText();
                            Log.e(TAG, "name " + name);
//                            pullParser.nextTag();
//                            Log.e(TAG, "name: end");
                        } else if ("version".equals(nodeName)){
//                            Log.e(TAG, "version: start");
                            version = pullParser.nextText();
                            Log.e(TAG, "version " + version);
//                            pullParser.nextTag();
//                            Log.e(TAG, "version: end");
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        Log.e(TAG, " END_TAG " );
                        if ("app".equals(nodeName)){
                            Log.e(TAG, "parseXMLWithPull: "+ "id "+id+" name "+name+" version "+version);
                        }
                        break;
                    default:
                        break;
                }
                eventType = pullParser.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void parseXmlWithSAX(){

        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            XMLReader xmlReader = factory.newSAXParser().getXMLReader();
            ContentHandler handler = new ContentHandler();
            xmlReader.setContentHandler(handler);
            xmlReader.parse(new InputSource(new StringReader(xmlData)));
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void parseXMLWithPull2() {
        try {
            AssetManager assetManager = getAssets();
            InputStream stream = assetManager.open("data.xml");
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser pullParser = factory.newPullParser();
            pullParser.setInput(stream, "UTF-8");
            int eventType = pullParser.getEventType();
            String id = "";
            String name = "";
            String version = "";
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String nodeName = pullParser.getName();
                switch (eventType) {
                    // 开始解析某个节点
                    case XmlPullParser.START_TAG:
                        if ("id".equals(nodeName)) {
                            id = pullParser.nextText();
                        }
                        else if ("name".equals(nodeName)) {
                            name = pullParser.nextText();
                        }
                        else if ("version".equals(nodeName)) {
                            version = pullParser.nextText();
                        }
                        break;
                    // 完成解析某个节点
                    case XmlPullParser.END_TAG:
                        if ("app".equals(nodeName)) {
                            Log.d("MainActivity", "id is " + id);
                            Log.d("MainActivity", "name is " + name);
                            Log.d("MainActivity", "version is " + version);
                        }
                    default:
                        break;
                }
                eventType = pullParser.next();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void parseXmlWithSAX2(){
        AssetManager assetManager = getAssets();
        InputStream stream;
        try {
             stream = assetManager.open("data.xml");
            SAXParserFactory factory = SAXParserFactory.newInstance();
            XMLReader xmlReader = factory.newSAXParser().getXMLReader();
            ContentHandler handler = new ContentHandler();
            xmlReader.setContentHandler(handler);
            xmlReader.parse(new InputSource(new StringReader(xmldata2)));

        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }

    }

    private void parswJsonWithJsonObject(){
        AssetManager assetManager = getAssets();
        try {
            InputStream stream = assetManager.open("jsondata.json");
            byte dataByte[] = new byte[stream.available()];

            stream.read(dataByte, 0, stream.available());
            String dataString = new String(dataByte);
            Log.e(TAG, "dataString: "+dataString );
            JSONArray jsonArray = new JSONArray(dataString);

            for (int i = 0; i < jsonArray.length(); i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");
                String version = jsonObject.getString("version");
                Log.e(TAG, "id: "+id+" name:"+name+" version:"+version );
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void parswJsonWithGson(){
        AssetManager assetManager = getAssets();
        InputStream stream = null;
        try {
            stream = assetManager.open("personJson.json");
            byte dataByte[] = new byte[stream.available()];
            stream.read(dataByte, 0, stream.available());
            String dataString = new String(dataByte);
            Log.e(TAG, "dataString: "+dataString );

            Gson gson = new Gson();
            Person person = gson.fromJson(dataString, Person.class);
            Log.e(TAG, person.toString() );
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void parswJsonArrayWithGson(){
        AssetManager assetManager = getAssets();
        InputStream stream = null;
        try {
            stream = assetManager.open("personArray.json");
            byte dataByte[] = new byte[stream.available()];
            stream.read(dataByte, 0, stream.available());
            String dataString = new String(dataByte);
            Log.e(TAG, "dataString: "+dataString );

            Gson gson = new Gson();
            List<Person> people = gson.fromJson(dataString, new TypeToken<List<Person>>(){}.getType());
            for (int i = 0; i < people.size(); i++){
                Log.e(TAG, " i "+i+" "+people.get(i));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}